import JSEncrypt from 'jsencrypt'
import { _axios } from './axios'

// const pubKey = `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx/pV3DZa92QOrWemsdFd
// bW3StXUXPP+wjzwUC0frfPiLIJyw0pkg6MmyysbqN1Ptt7paY9gBIQiggwYK7V+p
// YMj7mWP0R16ZJICs2pJqqtC5jbWgJyRajKwppWHjuPRIrzDtx3Cb1Ls3kbdopE28
// ikBJj8wXP0IOVXK9IlxXlU9to6HJZUBm5/fT+upiJViAcptlqb/lhtPKipeyMcJm
// sroXyaAGXmWC7Cc10Anv0rLIjU3fQkXg4VUQg5ja8bhYD1azkCTfw2tsqaYZygYU
// 5CIBtr67IrNtHHLHoHVqtKJPLSCc8ieHuQv+qHD76YASdcojX/jcrU7vfvVZZNwV
// uwIDAQAB`
let pubKey = ''
_axios({
  url: '/public-key',
  method: 'GET',
  params: { type: 'sm2' }
}).then(res => {
  // console.log('密钥', res)
  pubKey = res.data.Object['public-key']
})

/**
 * rsa加密
 * @param {string} str     原文
 * @param {string} keyCode 公钥
 * @returns {string} 加密后的文本
 */
export function getRsaCode(str) {
  const encryptStr = new JSEncrypt()

  // 设置 加密公钥
  encryptStr.setPublicKey(pubKey)
  // 进行加密
  const data = encryptStr
    .encryptLong(str.toString())
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
  return data
}
/**
 * rsa解密
 * @param {string} str     加密的文本
 * @returns {string} 解密后的文本
 */
export function getRsaDeCode(str) {
  let jsencrypt = new JSEncrypt()
  // 解密公钥
  jsencrypt.setPublicKey(pubKey)
  // 解密
  //分段采用decryptLong，不分段采用decrypt
  const decryptMsg = decodeURIComponent(
    jsencrypt.decryptLong(str.toString().replace(/-/g, '+').replace(/_/g, '/'))
  )
  return decryptMsg
}
